package com.bwie.auth.service.impl;

import com.bwie.auth.feign.SystemFeignService;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.domain.pojo.User;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Gd
 * @package: com.bwie.auth.service.impl
 * @Project: zg5_goods
 * @Name: AuthServiceImpl
 * @Date: 2024/4/29 17:09
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private SystemFeignService systemFeignService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 登录
     * @param user
     * @return
     */
    @Override
    public Result<JwtResponse> login(User user) {
        // 远程调用
        Result<User> byName = systemFeignService.findByName(user.getUserName());
        User data = byName.getData();
        if(data == null){
            return Result.error("用户不存在，请先注册");
        }
        // 判断密码
        if(!user.getUserPwd().equals(data.getUserPwd())){
            return Result.error("密码错误");
        }
        // 存用户信息
        redisTemplate.opsForValue().set(user.getUserName(), user.getUserPwd(),30, TimeUnit.MINUTES);
        // 生成token
        String userKey = UUID.randomUUID().toString();
        HashMap<String, Object> map = new HashMap<>();
        map.put(JwtConstants.USER_KEY , userKey);
        String token = JwtUtils.createToken(map);
        // 存token
        redisTemplate.opsForValue().set(user.getUserName(),token);
        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setExpirTime("720MIN");
        jwtResponse.setToken(token);
        // 登录成功  发送邮件 ---> 使用MQ
        rabbitTemplate.convertAndSend("Send_Email_To_Mq",data,message -> {
            message.getMessageProperties().setMessageId(UUID.randomUUID().toString());
            return message;
        });
        // 返回数据
        return Result.success(jwtResponse);
    }
}
